#pragma once
#include<iostream>
#include<string>
#include<cstring>
#include<unistd.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<sys/types.h>

namespace tcpclient
{
	class TcpClient
	{
		private:
			std::string dest_ip;
			uint16_t dest_port;
			int sock;
		public:
			TcpClient(std::string _ip,uint16_t _port):dest_ip(_ip),dest_port(_port),sock(-1){}
			void InitTcpClient()
			{
				sock = socket(AF_INET,SOCK_STREAM,0);
			}
			void Start()
			{
				struct sockaddr_in svr;
				svr.sin_family = AF_INET;
				svr.sin_port = htons(dest_port);
				svr.sin_addr.s_addr = inet_addr(dest_ip.c_str());

				if(connect(sock,(struct sockaddr*)&svr,sizeof(svr)) == 0)
					std::cout<<"connect success"<<std::endl;
				else
				{
					std::cout<<"connect failed"<<std::endl;
					return;
				}
				
				while(1)
				{

					std::string buffer;
					std::cout<<"请你输入# ";
					fflush(stdout);
					std::cin>>buffer;
					ssize_t s = buffer.size();
					if(s > 0)
					{
						write(sock,buffer.c_str(),buffer.size());
						char b[100];
						ssize_t msg_len = read(sock,b,sizeof(b)-1);
						if(msg_len > 0)
						{
							b[msg_len] = 0;
							std::cout<<b<<std::endl;
						}
						else
						{
							std::cout<<"server close"<<std::endl;
							break;
						}
					}
					else
					{
						std::cout<<"client input error!"<<std::endl;
						break;
					}
				}
			}
			~TcpClient()
			{
				if(sock >= 0)close(sock);
			}
	};
}
